import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/'
import { Dialog } from 'vant'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home' },
  {
    path: '/home',
    component: () => import('@/views/home/'),
    meta: {
      keepalive: true
    }
  },
  { path: '/register', component: () => import('@/views/register/') },
  { path: '/login', name: 'login', component: () => import('@/views/login/') },
  {
    path: '/userinfo',
    component: () => import('@/views/userinfo/'),
    meta: {
      istoken: true
    }
  },
  { path: '/article/:articleId', component: () => import('@/views/article/'), props: true },
  {
    path: '/edit',
    component: () => import('@/views/edit/'),
    meta: { istoken: true }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const { user } = store.state
  if (!user && to.meta.istoken) {
    Dialog.confirm({
      title: '访问提示',
      message: '该功能需要登录才能访问，确认登录吗'
    }).then(() => { // 确认执行这里
      router.replace({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
    }).catch(() => { // 取消执行这里
      // 取消了，中断路由导航
      next(false)
    })
  }
  next()
})
export default router
